from flask import Flask, render_template_string, request, redirect, url_for, session
from functools import wraps
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func
from flask import send_from_directory, flash
import requests
import os

app = Flask(__name__)
app.secret_key = 'your_secret_key'  # 用于session加密

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///default.db'  
app.config['SQLALCHEMY_BINDS'] = {
    'users': 'sqlite:///users.db',
    'forum': 'sqlite:///forum.db'
}
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLDER = os.path.join(BASE_DIR, 'repository')
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
ALLOWED_EXTENSIONS = {'pdf', 'doc', 'docx'}

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(BASE_DIR, 'default.db')
app.config['SQLALCHEMY_BINDS'] = {
    'users': 'sqlite:///' + os.path.join(BASE_DIR, 'users.db'),
    'forum': 'sqlite:///' + os.path.join(BASE_DIR, 'forum.db')
}
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# 论坛数据库
class ForumAnswer(db.Model):
    __bind_key__ = 'forum'
    id = db.Column(db.Integer, primary_key=True)
    post_id = db.Column(db.Integer, db.ForeignKey('forum_post.id'))
    answer = db.Column(db.Text, nullable=False)
    review_status = db.Column(db.String(10), default='未审核')  # '优质'/'普通'/'删除'/'未审核'
    created_at = db.Column(db.DateTime, server_default=db.func.now())

class ForumPost(db.Model):
    __bind_key__ = 'forum'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), nullable=False)
    question = db.Column(db.Text, nullable=False)
    teacher_answer = db.Column(db.Text, nullable=True)
    teacher_username = db.Column(db.String(80), nullable=True)  # 新增
    created_at = db.Column(db.DateTime, server_default=db.func.now())
    answers = db.relationship('ForumAnswer', backref='post', lazy=True)

# 用户数据库
class User(db.Model):
    __bind_key__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password = db.Column(db.String(120), nullable=False)
    role = db.Column(db.String(20), nullable=False)
    major = db.Column(db.String(120), nullable=True)

with app.app_context():
    db.create_all()
    # 测试管理员账号
    if not User.query.filter_by(username='1', role='管理员').first():
        admin = User(username='1', password='1', role='管理员', major='')
        db.session.add(admin)
        db.session.commit()

# 注册页面模板
register_template = '''
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>智问校园 - 注册</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            min-height: 100vh;
            background: linear-gradient(135deg, #e3f0ff 0%, #f8fbff 100%);
            font-family: "微软雅黑", Arial, sans-serif;
        }
        .register-container {
            width: 480px;
            margin: 80px auto;
            background: rgba(255,255,255,0.95);
            border-radius: 32px;
            box-shadow: 0 8px 32px #b3c6e0;
            padding: 48px 40px 36px 40px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .register-title {
            font-size: 38px;
            font-weight: bold;
            color: #2176ff;
            letter-spacing: 4px;
            margin-bottom: 36px;
        }
        .register-form {
            width: 100%;
            display: flex;
            flex-direction: column;
            gap: 22px;
        }
        .input-group {
            position: relative;
            display: flex;
            align-items: center;
        }
        .input-group input, .input-group select {
            width: 100%;
            padding: 14px 16px 14px 44px;
            border: none;
            border-radius: 24px;
            background: #f3f7fa;
            font-size: 18px;
            outline: none;
        }
        .input-group .icon {
            position: absolute;
            left: 14px;
            font-size: 20px;
            color: #2176ff;
        }
        .register-btns {
            display: flex;
            gap: 18px;
            margin-top: 16px;
        }
        .register-btn, .login-btn {
            flex: 1;
            padding: 12px 0;
            border-radius: 24px;
            font-size: 20px;
            border: none;
            cursor: pointer;
            transition: background 0.2s;
        }
        .register-btn {
            background: linear-gradient(90deg, #2176ff 0%, #5ec6fa 100%);
            color: #fff;
        }
        .register-btn:hover {
            background: linear-gradient(90deg, #1764c0 0%, #3bb6e0 100%);
        }
        .login-btn {
            background: #fff;
            color: #2176ff;
            border: 2px solid #2176ff;
        }
        .login-btn:hover {
            background: #e3f0ff;
        }
        .tips {
            margin-top: 10px;
            color: #888;
            font-size: 14px;
            text-align: left;
        }
        .error {
            color: #e74c3c;
            text-align: center;
            margin-bottom: 10px;
        }
        .success {
            color: green;
            text-align: center;
            margin-bottom: 10px;
        }
        @media (max-width: 600px) {
            .register-container { width: 98vw; padding: 24px 4vw; }
        }
    </style>
    <link rel="stylesheet" href="https://at.alicdn.com/t/c/font_8d5l8fzk5b87iudi.css">
</head>
<body>
    <div class="register-container">
        <div class="register-title">智问校园</div>
        {% if error %}<div class="error">{{ error }}</div>{% endif %}
        {% if success %}<div class="success">{{ success }}</div>{% endif %}
        <form class="register-form" method="post">
            <div class="input-group">
                <span class="icon">&#xe60d;</span>
                <input type="text" name="username" placeholder="用户名" required>
            </div>
            <div class="input-group">
                <span class="icon">&#xe60e;</span>
                <input type="password" name="password" placeholder="密码" required>
            </div>
            <div class="input-group">
                <span class="icon">&#xe66f;</span>
                <input type="text" name="major" placeholder="专业/兴趣" required>
            </div>
            <div class="input-group">
                <span class="icon">&#xe6b8;</span>
                <select name="role" required>
                    <option value="" disabled selected>请选择身份</option>
                    <option value="学生">学生</option>
                    <option value="教师">教师</option>
                </select>
            </div>
            <div class="register-btns">
                <button type="submit" class="register-btn">注册</button>
                <a href="{{ url_for('login') }}" class="login-btn" style="text-align:center;line-height:44px;text-decoration:none;">登录</a>
            </div>
        </form>
        <div class="tips">
            已有账号？<a href="{{ url_for('login') }}" style="color:#2176ff;text-decoration:underline;">去登录</a>
        </div>
    </div>
</body>
</html>
'''

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'username' not in session:
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function

# 注册路由
@app.route('/register', methods=['GET', 'POST'])
def register():
    error = ''
    success = ''
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        role = request.form.get('role')
        major = request.form.get('major')  # 新增
        if role not in ['学生', '教师']:
            error = '只能注册学生或教师账号'
        elif User.query.filter_by(username=username).first():
            error = '用户名已存在'
        else:
            user = User(username=username, password=password, role=role, major=major)
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('login'))
    return render_template_string(register_template, error=error, success=success)

# 修改登录模板，增加注册链接
login_template = '''
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>智问校园 - 登录</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            min-height: 100vh;
            background: linear-gradient(135deg, #e3f0ff 0%, #f8fbff 100%);
            font-family: "微软雅黑", Arial, sans-serif;
        }
        .login-container {
            width: 480px;
            margin: 80px auto;
            background: rgba(255,255,255,0.95);
            border-radius: 32px;
            box-shadow: 0 8px 32px #b3c6e0;
            padding: 48px 40px 36px 40px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .login-title {
            font-size: 38px;
            font-weight: bold;
            color: #2176ff;
            letter-spacing: 4px;
            margin-bottom: 36px;
        }
        .login-form {
            width: 100%;
            display: flex;
            flex-direction: column;
            gap: 22px;
        }
        .input-group {
            position: relative;
            display: flex;
            align-items: center;
        }
        .input-group input, .input-group select {
            width: 100%;
            padding: 14px 16px 14px 44px;
            border: none;
            border-radius: 24px;
            background: #f3f7fa;
            font-size: 18px;
            outline: none;
        }
        .input-group .icon {
            position: absolute;
            left: 14px;
            font-size: 20px;
            color: #2176ff;
        }
        .login-btns {
            display: flex;
            gap: 18px;
            margin-top: 16px;
        }
        .login-btn, .register-btn {
            flex: 1;
            padding: 12px 0;
            border-radius: 24px;
            font-size: 20px;
            border: none;
            cursor: pointer;
            transition: background 0.2s;
        }
        .login-btn {
            background: linear-gradient(90deg, #2176ff 0%, #5ec6fa 100%);
            color: #fff;
        }
        .login-btn:hover {
            background: linear-gradient(90deg, #1764c0 0%, #3bb6e0 100%);
        }
        .register-btn {
            background: #fff;
            color: #2176ff;
            border: 2px solid #2176ff;
        }
        .register-btn:hover {
            background: #e3f0ff;
        }
        .tips {
            margin-top: 10px;
            color: #888;
            font-size: 14px;
            text-align: left;
        }
        .error {
            color: #e74c3c;
            text-align: center;
            margin-bottom: 10px;
        }
        @media (max-width: 600px) {
            .login-container { width: 98vw; padding: 24px 4vw; }
        }
    </style>
    <!-- 引入阿里巴巴矢量图标库（可选） -->
    <link rel="stylesheet" href="https://at.alicdn.com/t/c/font_8d5l8fzk5b87iudi.css">
</head>
<body>
    <div class="login-container">
        <div class="login-title">智问校园</div>
        {% if error %}<div class="error">{{ error }}</div>{% endif %}
        <form class="login-form" method="post">
            <div class="input-group">
                <span class="icon">&#xe60d;</span>
                <input type="text" name="username" placeholder="用户名" required>
            </div>
            <div class="input-group">
                <span class="icon">&#xe60e;</span>
                <input type="password" name="password" placeholder="密码" required>
            </div>
            <div class="input-group">
                <span class="icon">&#xe6b8;</span>
                <select name="role" required>
                    <option value="" disabled selected>请选择身份</option>
                    <option value="学生">学生</option>
                    <option value="教师">教师</option>
                    <option value="管理员">管理员</option>
                </select>
            </div>
            <div class="login-btns">
                <button type="submit" class="login-btn">登录</button>
                <a href="{{ url_for('register') }}" class="register-btn" style="text-align:center;line-height:44px;text-decoration:none;">注册</a>
            </div>
        </div>
    </div>
</body>
</html>
'''

# 登录路由
@app.route('/login', methods=['GET', 'POST'])
def login():
    error = ''
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        role = request.form.get('role')
        user = User.query.filter_by(username=username, role=role).first()
        if user and user.password == password:
            session['username'] = username
            session['role'] = role
            session['major'] = user.major
            if role == '教师':
                return redirect(url_for('teacher_home'))
            elif role == '管理员':
                return redirect(url_for('admin_home'))
            else:
                return redirect(url_for('home'))
        else:
            error = '用户名、密码或角色错误'
    return render_template_string(login_template, error=error)

# 主页（需登录后访问）
@app.route('/', methods=['GET', 'POST'])
@login_required
def home():
    question = ""
    answer = ""
    forum_answers = []
    if request.method == 'POST':
        question = request.form.get('question', '')
        answer = get_answer(question, mode="简洁")
    # 新增：将问题和AI答复写入论坛
        if request.method == 'POST':
            question = request.form.get('question', '')
            answer = get_answer(question, mode="简洁")
            # 修改：所有身份都写入AI答复
            if question and answer:
                post = ForumPost(
                    username=session.get('username'),
                    question=question
                )
                db.session.add(post)
                db.session.commit()
                forum_answer = ForumAnswer(
                    post_id=post.id,
                    answer=answer,
                    review_status='未审核'
                )
                db.session.add(forum_answer)
                db.session.commit()
                print("已写入论坛：", question, answer)
    role = session.get('role')
    if role == '学生':
        major = session.get('major', '')
        recommended_questions = generate_excellent_questions(major, 5)
        personalized_resources = generate_personalized_resources(major, 5)
        teacher_best_answers = []
        if question:
        # 查所有同名问题的id
            post_ids = [p.id for p in ForumPost.query.filter_by(question=question).all()]
            teacher_best_answers = []
            if post_ids:
                teacher_best_answers = [
                    ans.answer for ans in ForumAnswer.query.filter(
                        ForumAnswer.post_id.in_(post_ids),
                        ForumAnswer.review_status == '优质'
                    ).all()
                ]
        return render_template_string(
            student_template,
            recommended_questions=recommended_questions,
            sidebar_modules=sidebar_modules,
            question=question,
            answer=answer,
            forum_answers=forum_answers,
            personalized_resources=personalized_resources,
            teacher_best_answers=teacher_best_answers
        )
    elif role == '教师':
        return render_template_string(teacher_template, sidebar_modules=sidebar_modules)
    elif role == '管理员':
        return render_template_string(admin_template)
    else:
        return "未知角色，无法访问", 403

# 教师主页：待回答、已回答、AI答复审核
@app.route('/teacher', methods=['GET'])
@login_required
def teacher_home():
    if session.get('role') != '教师':
        return redirect(url_for('home'))
    major = session.get('major', '')
    # 获取所有问题，按内容分组
    posts = ForumPost.query.order_by(ForumPost.created_at.desc()).all()
    question_map = {}
    for post in posts:
        if not is_question_related_to_major(post.question, major):
            continue
        q = post.question
        if q not in question_map:
            question_map[q] = []
        question_map[q].append(post.id)
    to_review, reviewed = [], []
    for q, post_ids in question_map.items():
        # 查所有同名问题的所有AI答复
        answers = ForumAnswer.query.filter(ForumAnswer.post_id.in_(post_ids)).all()
        if not answers:
            continue
        if any(ans.review_status == '未审核' for ans in answers):
            to_review.append({'question': q, 'post_ids': post_ids})
        else:
            reviewed.append({'question': q, 'post_ids': post_ids})
    # 当前选中问题
    selected_question = request.args.get('question')
    selected_post_ids = []
    selected_answers = []
    if selected_question:
        selected_post_ids = question_map.get(selected_question, [])
        selected_answers = ForumAnswer.query.filter(
            ForumAnswer.post_id.in_(selected_post_ids)
        ).all()
    return render_template_string(
        teacher_template,
        sidebar_modules=sidebar_modules,
        to_review=to_review,
        reviewed=reviewed,
        selected_question=selected_question,
        selected_answers=selected_answers
    )

# 教师审核AI答复
@app.route('/teacher/review_answer/<int:answer_id>', methods=['POST'])
@login_required
def review_answer(answer_id):
    if session.get('role') != '教师':
        return redirect(url_for('home'))
    status = request.form.get('status')
    answer = ForumAnswer.query.get(answer_id)
    if answer:
        if status == '删除':
            db.session.delete(answer)
        else:
            answer.review_status = status
        db.session.commit()
    return redirect(url_for('teacher_home', post_id=answer.post_id))

# 登出
@app.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('login'))

# 学生主页模板
student_template = '''
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>学生智能问答与知识服务平台</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: "微软雅黑", Arial, sans-serif;
            background: #fff;
        }
        .sidebar {
            width: 200px;
            background: #2566c6;
            color: #fff;
            min-height: 100vh;
            float: left;
            border-radius: 24px 0 0 24px;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding-top: 0;
            position: relative;
        }
        .sidebar h2 {
            font-size: 22px;
            margin: 24px 0 24px 0;
            background: #1e4e9e;
            border-radius: 16px;
            width: 160px;
            text-align: center;
            padding: 8px 0;
            font-weight: normal;
        }
        .sidebar ul {
            list-style: none;
            padding: 0;
            width: 100%;
        }
        .sidebar li {
            margin: 18px auto;
            width: 160px;
            height: 40px;
            background: #fff;
            color: #2566c6;
            border-radius: 20px;
            text-align: center;
            line-height: 40px;
            font-size: 18px;
            cursor: pointer;
            transition: background 0.2s, color 0.2s;
            border: 2px solid #2566c6;
        }
        .sidebar li:hover {
            background: #e3f0ff;
            color: #1e4e9e;
        }
        .main {
            margin-left: 200px;
            padding: 0 40px;
        }
        .header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 32px;
        }
        .logo-box {
            display: flex;
            align-items: center;
        }
        .logo-img {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: #fff;
            border: 2px solid #2566c6;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 28px;
            font-weight: bold;
            color: #2566c6;
            margin-right: 12px;
        }
        .logo-title {
            font-size: 36px;
            font-weight: bold;
            color: #2566c6;
            letter-spacing: 2px;
        }
        .user-center {
            font-size: 20px;
            color: #222;
            background: #fff;
            border-radius: 20px;
            padding: 8px 24px 8px 40px;
            background-image: url('https://img.icons8.com/ios-filled/50/2566c6/user-male-circle.png');
            background-size: 24px 24px;
            background-repeat: no-repeat;
            background-position: 10px center;
            border: 1px solid #2566c6;
            cursor: pointer;
            margin-top: 0;
        }
        .title {
            text-align: center;
            font-size: 38px;
            margin: 32px 0 24px 0;
            font-weight: 500;
        }
        .search-box {
            display: flex;
            justify-content: center;
            margin-bottom: 32px;
        }
        .search-box input[type="text"] {
            width: 700px;
            padding: 18px;
            font-size: 22px;
            border: none;
            border-radius: 16px 0 0 16px;
            background: #f4f8fb;
            outline: none;
            color: #666;
            border: 2px solid #bfc9d9;
        }
        .search-box button {
            padding: 0 36px;
            border: none;
            background: #a0aec0;
            color: #fff;
            font-size: 22px;
            border-radius: 0 16px 16px 0;
            cursor: pointer;
            transition: background 0.2s;
            border: 2px solid #bfc9d9;
            border-left: none;
        }
        .search-box button:hover {
            background: #2566c6;
        }
        .panel-row {
            display: flex;
            justify-content: center;
            gap: 40px;
            margin-top: 32px;
        }
        .panel {
            background: #eaf6fd;
            border-radius: 12px;
            box-shadow: 0 2px 8px #e0e7ef;
            width: 480px;
            min-height: 220px;
            padding: 0 0 24px 0;
            border: 2px solid #bfc9d9;
            position: relative;
        }
        .panel .panel-header {
            background: #f4faff;
            border-radius: 12px 12px 0 0;
            font-size: 28px;
            font-weight: 500;
            text-align: center;
            padding: 12px 0;
            border-bottom: 1px solid #bfc9d9;
            margin-bottom: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .panel .panel-header .circle {
            width: 28px;
            height: 28px;
            border-radius: 50%;
            border: 2px dashed #b3c6e0;
            margin-right: 12px;
            display: inline-block;
        }
        .panel ul {
            margin: 0 24px;
            padding: 0;
            list-style: none;
        }
        .panel ul li {
            font-size: 19px;
            color: #333;
            margin-bottom: 10px;
            line-height: 1.7;
        }
        .logout-link {
            position: absolute;
            top: 32px;
            right: 40px;
            color: #2566c6;
            font-size: 18px;
            text-decoration: underline;
        }
        @media (max-width: 1100px) {
            .main { margin-left: 0; padding: 0 10px; }
            .panel-row { flex-direction: column; align-items: center; gap: 24px; }
            .panel { width: 98vw; }
        }
    </style>
</head>
<body>
    <div style="display:flex;">
        <div class="sidebar">
            <h2>功能导航</h2>
            <ul>
                {% for module in sidebar_modules %}
                    {% if module == "知识库管理" or module == "知识库" %}
                        <li>
                            <a href="{{ url_for('repository') }}" style="color:#2566c6;text-decoration:none;display:block;width:100%;height:100%;">知识库</a>
                        </li>
                    {% else %}
                        <li>{{ module }}</li>
                    {% endif %}
                {% endfor %}
                <li><a href="{{ url_for('forum_page') }}" style="color:#2566c6;text-decoration:none;">论坛</a></li>
                <li><a href="{{ url_for('logout') }}" style="color:#2566c6;text-decoration:none;">退出登录</a></li>
             </ul>
        </div>
        <div class="main" style="width:100%;">
            <div class="header">
                <div class="logo-box">
                    <img src="{{ url_for('static', filename='logo_title.png') }}" alt="logo" style="height:70px;margin-right:12px;">
                    <div class="logo-title">智问校园</div>
                </div>
                <a href="{{ url_for('profile') }}" class="user-center">个人中心</a>
            </div>
            <div class="title">学生智能问答与知识服务平台</div>
            <form class="search-box" method="post">
                <input type="text" name="question" placeholder="请输入学术问题或学习问题" value="{{ question|default('') }}">
                <button type="submit">搜索</button>
            </form>

            {% if question %}
            <div class="panel-row">
                <div class="panel">
                    <div class="panel-header"><span class="circle"></span>ai实时解答</div>
                    <div class="panel-content" style="min-height:180px;">
                        {% if answer %}
                            <div>{{ answer }}</div>
                        {% else %}
                            <div style="color:#aaa;">暂无AI解答</div>
                        {% endif %}
                    </div>
                </div>
                <div class="panel">
                    <div class="panel-header"><span class="circle"></span>教师审核解答</div>
                    <div class="panel-content" style="min-height:180px;">
                        {% if teacher_best_answers %}
                            {% for ans in teacher_best_answers %}
                                <div>{{ ans }}</div>
                            {% endfor %}
                        {% else %}
                            <div style="color:#aaa;">暂无教师审核解答</div>
                        {% endif %}
                    </div>
                </div>
            </div>
            {% endif %}

            <div class="panel-row">
                <div class="panel">
                    <div class="panel-header"><span class="circle"></span>推荐问题与主题导航</div>
                    <ul>
                        {% for q in recommended_questions %}
                        <li>{{ q }}</li>
                        {% endfor %}
                    </ul>
                </div>
                <div class="panel">
                    <div class="panel-header"><span class="circle"></span>个性化学习资源推荐</div>
                    <ul>
                        {% for res in personalized_resources %}
                        <li>{{ res }}</li>
                        {% endfor %}
                    </ul>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
'''

# 教师主页模板
teacher_template = '''
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>教师智能问答与知识服务平台</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: "微软雅黑", Arial, sans-serif;
            background: #fff;
        }
        .sidebar {
            width: 220px;
            background: #2566c6;
            color: #fff;
            min-height: 100vh;
            float: left;
            border-radius: 24px 0 0 24px;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding-top: 0;
            position: relative;
        }
        .sidebar h2 {
            font-size: 22px;
            margin: 24px 0 24px 0;
            background: #1e4e9e;
            border-radius: 16px;
            width: 180px;
            text-align: center;
            padding: 8px 0;
            font-weight: normal;
        }
        .sidebar ul {
            list-style: none;
            padding: 0;
            width: 100%;
        }
        .sidebar li {
            margin: 18px auto;
            width: 180px;
            height: 40px;
            background: #fff;
            color: #2566c6;
            border-radius: 20px;
            text-align: center;
            line-height: 40px;
            font-size: 18px;
            cursor: pointer;
            transition: background 0.2s, color 0.2s;
            border: 2px solid #2566c6;
        }
        .sidebar li:hover {
            background: #e3f0ff;
            color: #1e4e9e;
        }
        .main {
            margin-left: 220px;
            padding: 0 40px;
        }
        .header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 32px;
        }
        .logo-box {
            display: flex;
            align-items: center;
        }
        .logo-img {
            height: 70px;
            margin-right: 12px;
        }
        .user-center {
            font-size: 20px;
            color: #222;
            background: #fff;
            border-radius: 20px;
            padding: 8px 24px 8px 40px;
            background-image: url('https://img.icons8.com/ios-filled/50/2566c6/user-male-circle.png');
            background-size: 24px 24px;
            background-repeat: no-repeat;
            background-position: 10px center;
            border: 1px solid #2566c6;
            cursor: pointer;
            margin-top: 0;
            text-decoration: none;
        }
        .greeting {
            text-align: right;
            color: #888;
            font-size: 18px;
            margin-top: 10px;
        }
        .title {
            text-align: center;
            font-size: 38px;
            margin: 24px 0 24px 0;
            font-weight: 500;
        }
        .panel-row {
            display: flex;
            justify-content: center;
            gap: 40px;
            margin-top: 32px;
        }
        .panel {
            background: #eaf6fd;
            border-radius: 12px;
            box-shadow: 0 2px 8px #e0e7ef;
            width: 350px;
            min-height: 420px;
            padding: 0 0 24px 0;
            border: 2px solid #bfc9d9;
            position: relative;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .panel .panel-header {
            background: #f4faff;
            border-radius: 12px 12px 0 0;
            font-size: 24px;
            font-weight: 500;
            text-align: center;
            padding: 12px 0;
            border-bottom: 1px solid #bfc9d9;
            margin-bottom: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
        }
        .panel .panel-header .circle {
            width: 28px;
            height: 28px;
            border-radius: 50%;
            border: 2px dashed #b3c6e0;
            margin-right: 12px;
            display: inline-block;
        }
        .panel-content {
            width: 90%;
            min-height: 320px;
            background: #f4faff;
            border-radius: 8px;
            margin: 0 auto;
            border: 2px solid #b3c6e0;
            margin-top: 10px;
            overflow-y: auto;
            max-height: 350px;
        }
        .question-link {
            color: #2566c6;
            text-decoration: underline;
            cursor: pointer;
        }
        .ai-answer {
            margin: 10px 0;
            padding: 8px 12px;
            background: #fff;
            border-radius: 6px;
            border: 1px solid #e0e7ef;
        }
        .ai-answer.优质 {
            font-weight: bold;
            border: 2px solid #2176ff;
            background: #e3f0ff;
        }
        .ai-answer.普通 {
            font-weight: normal;
        }
        .ai-answer.未审核 {
            background: #fffbe6;
        }
        .ai-answer .status {
            color: #888;
            margin-left: 8px;
        }
        .ai-answer form {
            display: inline;
            margin-left: 10px;
        }
        ul.question-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        ul.question-list li {
            margin-bottom: 10px;
        }
        @media (max-width: 1200px) {
            .main { margin-left: 0; padding: 0 10px; }
            .panel-row { flex-direction: column; align-items: center; gap: 24px; }
            .panel { width: 98vw; }
        }
    </style>
</head>
<body>
    <div style="display:flex;">
        <div class="sidebar">
            <h2>功能导航</h2>
            <ul>
                {% for module in sidebar_modules %}
                    {% if module == "知识库管理" or module == "知识库" %}
                        <li>
                            <a href="{{ url_for('repository') }}" style="color:#2566c6;text-decoration:none;display:block;width:100%;height:100%;">知识库管理</a>
                        </li>
                    {% else %}
                        <li>{{ module }}</li>
                    {% endif %}
                {% endfor %}
                <li><a href="{{ url_for('forum_page') }}" style="color:#2566c6;text-decoration:none;">论坛</a></li>
                <li><a href="{{ url_for('logout') }}" style="color:#2566c6;text-decoration:none;">退出登录</a></li>
            </ul>
        </div>
        <div class="main" style="width:100%;">
            <div class="header">
                <div class="logo-box">
                    <img src="{{ url_for('static', filename='logo_title.png') }}" alt="logo" class="logo-img">
                    <div class="logo-title" style="font-size:32px;color:#2566c6;font-weight:bold;">智问校园</div>
                </div>
                <a href="{{ url_for('profile') }}" class="user-center">个人中心</a>
            </div>
            <div class="greeting">{{ session['username'] }}老师，{{ greeting|default('下午好') }}！</div>
            <div class="title">教师智能问答与知识服务平台</div>
            <div class="panel-row">
                <!-- 已审核问题 -->
                <div class="panel">
                    <div class="panel-header"><span class="circle"></span>已审核问题</div>
                    <div class="panel-content">
                        <ul class="question-list">
                        {% for item in reviewed %}
                            <li>
                                <a class="question-link" href="{{ url_for('teacher_home', question=item.question) }}">{{ item.question }}</a>
                            </li>
                        {% else %}
                            <li style="color:#aaa;">暂无</li>
                        {% endfor %}
                        </ul>
                    </div>
                </div>
                <!-- AI回答审核 -->
                <div class="panel">
                    <div class="panel-header"><span class="circle"></span>AI回答审核</div>
                    <div class="panel-content">
                        {% if selected_question %}
                            <div style="font-weight:bold;margin-bottom:10px;">{{ selected_question }}</div>
                            {% for ans in selected_answers %}
                                <div class="ai-answer {{ ans.review_status }}">
                                    {{ ans.answer }}
                                    <form method="post" action="{{ url_for('review_answer', answer_id=ans.id) }}">
                                        <button name="status" value="优质" {% if ans.review_status=='优质' %}disabled{% endif %}>优质</button>
                                        <button name="status" value="普通" {% if ans.review_status=='普通' %}disabled{% endif %}>普通</button>
                                        <button name="status" value="删除">删除</button>
                                    </form>
                                    {% if ans.review_status != '未审核' %}
                                        <span class="status">({{ ans.review_status }})</span>
                                    {% endif %}
                                </div>
                            {% else %}
                                <div style="color:#aaa;">暂无AI答复</div>
                            {% endfor %}
                        {% else %}
                            <div style="color:#888;">请在左/右侧选择一个待审核或已回答问题</div>
                        {% endif %}
                    </div>
                </div>
                <!-- 待审核问题 -->
                <div class="panel">
                    <div class="panel-header"><span class="circle"></span>待审核问题</div>
                    <div class="panel-content">
                        <ul class="question-list">
                        {% for item in to_review %}
                            <li>
                                <a class="question-link" href="{{ url_for('teacher_home', question=item.question) }}">{{ item.question }}</a>
                            </li>
                        {% else %}
                            <li style="color:#aaa;">暂无</li>
                        {% endfor %}
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
'''

# 管理员主页模板
admin_template = '''
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>管理员主页</title>
    <style>
        body { font-family: "微软雅黑", Arial, sans-serif; margin: 0; background: #f5f6fa;}
        .container { display: flex; }
        .sidebar {
            width: 220px; background: #2d3a4b; color: #fff; min-height: 100vh; padding: 30px 0;
        }
        .sidebar h2 { text-align: center; font-size: 22px; margin-bottom: 30px;}
        .sidebar ul { list-style: none; padding: 0;}
        .sidebar li { padding: 12px 30px; cursor: pointer;}
        .sidebar li:hover { background: #1a2230;}
        .main { flex: 1; padding: 40px 60px;}
    </style>
</head>
<body>
    <div class="container">
        <div class="sidebar">
            <h2>功能导航</h2>
            <ul>
                <li><a href="{{ url_for('admin_repository') }}" style="color:#fff;">知识库管理</a></li>
                <li><a href="{{ url_for('admin_forum') }}" style="color:#fff;">论坛管理</a></li>
                <li><a href="{{ url_for('logout') }}" style="color:#fff;">退出登录</a></li>
            </ul>
        </div>
        <div class="main">
            <h1>管理员智能问答与知识服务平台</h1>
            <div style="margin-top:40px;">
                <h2>欢迎，管理员 {{ session['username'] }}</h2>
                <p>请选择左侧功能进行管理。</p>
            </div>
        </div>
    </div>
</body>
</html>
'''

# 管理员知识库管理页面模板
admin_repository_template = '''
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>知识库管理</title>
</head>
<body>
    <h2>知识库文件管理</h2>
    <ul>
        {% for f in files %}
        <li>
            <a href="{{ url_for('download_file', filename=f) }}">{{ f }}</a>
            <form method="post" action="{{ url_for('admin_delete_file', filename=f) }}" style="display:inline;">
                <button type="submit" onclick="return confirm('确定要删除该文件吗？')">删除</button>
            </form>
        </li>
        {% endfor %}
    </ul>
    <a href="{{ url_for('admin_home') }}">返回管理员主页</a>
</body>
</html>
'''

# 管理员论坛管理页面模板
admin_forum_template = '''
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>论坛管理</title>
</head>
<body>
    <h2>论坛内容管理</h2>
    <ul>
        {% for post in posts %}
        <li style="margin-bottom:20px;">
            <b>问题：</b>{{ post.question }}（by {{ post.username }}）
            <form method="post" action="{{ url_for('admin_delete_post', post_id=post.id) }}" style="display:inline;">
                <button type="submit" onclick="return confirm('确定要删除该问题及其所有回答吗？')">删除问题</button>
            </form>
            <ul>
                {% for ans in post.answers %}
                <li>
                    <b>AI答复：</b>{{ ans.answer }}
                    <form method="post" action="{{ url_for('admin_delete_answer', post_id=post.id, answer_id=ans.id) }}" style="display:inline;">
                        <button type="submit" onclick="return confirm('确定要删除该AI答复吗？')">删除答复</button>
                    </form>
                    <span style="color:#888;">（审核状态：{{ ans.review_status }}）</span>
                </li>
                {% endfor %}
                {% if post.teacher_answer %}
                <li>
                    <b>教师答复：</b>{{ post.teacher_answer }}
                    <form method="post" action="{{ url_for('admin_delete_teacher_answer', post_id=post.id) }}" style="display:inline;">
                        <button type="submit" onclick="return confirm('确定要删除该教师答复吗？')">删除答复</button>
                    </form>
                </li>
                {% endif %}
            </ul>
        </li>
        {% endfor %}
    </ul>
    <a href="{{ url_for('admin_home') }}">返回管理员主页</a>
</body>
</html>
'''

# 新增论坛页面模板
forum_template = '''
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>学生论坛</title>
    <style>
        body { font-family: "微软雅黑", Arial, sans-serif; background: #f5f6fa; }
        .forum-box { width: 800px; margin: 40px auto; background: #fff; border-radius: 8px; box-shadow: 0 2px 8px #eee; padding: 40px;}
        h2 { text-align: center; }
        .q { font-weight: bold; margin-top: 20px;}
        .a { margin-left: 20px; color: #333;}
        .divider { border-bottom: 1px solid #eee; margin: 18px 0;}
    </style>
</head>
<body>
    <div class="forum-box">
    <h2>学生论坛</h2>
    {% if is_teacher %}
    <div style="background:#eaf0fb;padding:10px 20px;margin-bottom:20px;">
        <strong>热点问题推荐：</strong>
        <ul>
            {% for q, count in hot_questions %}
            <li>{{ q }}（被提问{{ count }}次）</li>
            {% endfor %}
        </ul>
    </div>
    {% endif %}
    {% for item in forum %}
        <div class="q">Q: {{ item.question }}</div>
        {% for ans in item.answers %}
            <div class="a">AI答复: {{ ans }}</div>
        {% endfor %}
        {% if item.teacher_answer %}
            <div class="a" style="color:green;">教师回复: {{ item.teacher_answer }}</div>
        {% endif %}
        {% if is_teacher %}
            <form method="post" style="margin-top:10px;">
                <input type="hidden" name="post_id" value="{{ item.id }}">
                <textarea name="teacher_answer" placeholder="教师回复..." style="width:90%;">{{ item.teacher_answer or '' }}</textarea>
                <button type="submit">提交教师回复</button>
            </form>
        {% endif %}
        <div class="divider"></div>
    {% endfor %}
    <div style="text-align:center;">
        <a href="{{ url_for('home') }}">返回主页</a>
    </div>
</div>
</body>
</html>
'''

# 优化知识库页面：右侧排列、无侧边栏、支持检索，只有教师可上传，学生仅可下载
repository_template = '''
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>在线知识库</title>
    <style>
        body { font-family: "微软雅黑", Arial, sans-serif; margin: 0; background: #fff;}
        .header-bar {
            display: flex; align-items: center; justify-content: space-between;
            padding: 18px 40px 0 40px;
        }
        .logo-box { display: flex; align-items: center; }
        .logo-img { height: 56px; margin-right: 12px; }
        .logo-title { font-size: 32px; color: #2566c6; font-weight: bold; }
        .main-title {
            text-align: center;
            font-size: 32px;
            font-weight: bold;
            margin: 18px 0 18px 0;
            color: #2566c6;
            letter-spacing: 2px;
        }
        .user-center-btn {
            display: flex;
            align-items: center;
            border: 2px solid #2566c6;
            border-radius: 12px;
            padding: 4px 18px 4px 10px;
            background: #fff;
            color: #2566c6;
            font-size: 22px;
            text-decoration: none;
            transition: background 0.2s, box-shadow 0.2s;
            box-shadow: 0 2px 6px #e0e7ef;
        }
        .user-center-btn:hover {
            background: #eaf6fd;
        }
        .user-center-btn svg {
            margin-right: 8px;
        }
        /* ...其余样式不变... */
        .search-bar {
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 0 auto 24px auto;
            width: 80%;
        }
        .search-bar input[type="text"] {
            flex: 1;
            padding: 14px 18px;
            font-size: 18px;
            border: 2px solid #bfc9d9;
            border-radius: 8px 0 0 8px;
            outline: none;
        }
        .search-bar button {
            padding: 14px 32px;
            border: none;
            background: #2566c6;
            color: #fff;
            font-size: 18px;
            border-radius: 0 8px 8px 0;
            cursor: pointer;
            border: 2px solid #2566c6;
            border-left: none;
        }
        .repository-box {
            width: 90%;
            margin: 0 auto;
            background: #f5f8fc;
            border-radius: 12px;
            box-shadow: 0 2px 8px #e0e7ef;
            padding: 32px 32px 24px 32px;
        }
        .file-table {
            width: 100%;
            border-collapse: collapse;
            background: #fff;
            margin-top: 18px;
        }
        .file-table th, .file-table td {
            border: 1px solid #bfc9d9;
            padding: 12px 10px;
            text-align: left;
        }
        .file-table th {
            background: #eaf6fd;
            font-size: 18px;
        }
        .file-table td {
            font-size: 16px;
        }
        .upload-form {
            margin-bottom: 18px;
        }
        .upload-form input[type="file"] {
            font-size: 16px;
        }
        .upload-form button {
            padding: 6px 18px;
            border-radius: 6px;
            border: none;
            background: #2566c6;
            color: #fff;
            font-size: 16px;
            cursor: pointer;
            margin-left: 10px;
        }
        .upload-form button:hover {
            background: #1e4e9e;
        }
        .back-link {
            display: inline-block;
            margin-top: 18px;
            color: #2566c6;
            text-decoration: underline;
            font-size: 16px;
        }
        @media (max-width: 900px) {
            .repository-box { width: 99vw; padding: 10px 2vw; }
            .header-bar { flex-direction: column; align-items: flex-start; padding: 10px 2vw 0 2vw;}
            .main-title { font-size: 22px; }
        }
    </style>
</head>
<body>
    <div class="header-bar">
        <div class="logo-box">
            <img src="{{ url_for('static', filename='logo_title.png') }}" alt="logo" class="logo-img">
            <div class="logo-title">智问校园</div>
        </div>
        <a href="{{ url_for('profile') }}" class="user-center-btn">
            <svg width="28" height="28" viewBox="0 0 1024 1024" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle cx="512" cy="512" r="480" stroke="#2566c6" stroke-width="32" fill="none"/>
                <circle cx="512" cy="400" r="120" fill="#2566c6"/>
                <ellipse cx="512" cy="700" rx="200" ry="120" fill="#2566c6"/>
            </svg>
            个人中心
        </a>
    </div>
    <div class="main-title">在线知识库</div>
    <div class="repository-box">
        <form class="search-bar" method="get">
            <input type="text" name="q" placeholder="输入关键词检索知识库文件" value="{{ keyword|default('') }}">
            <button type="submit">搜索</button>
        </form>
        {% if can_upload %}
        <form class="upload-form" method="post" enctype="multipart/form-data">
            <input type="file" name="files" multiple accept=".pdf,.doc,.docx">
            <button type="submit">上传</button>
        </form>
        {% endif %}
        <table class="file-table">
            <tr>
                <th>文件名</th>
                <th>操作</th>
            </tr>
            {% for f in files %}
            <tr>
                <td>{{ f }}</td>
                <td>
                    <a href="{{ url_for('download_file', filename=f) }}">下载</a>
                </td>
            </tr>
            {% else %}
            <tr>
                <td colspan="2" style="color:#aaa;">暂无文件</td>
            </tr>
            {% endfor %}
        </table>
        <a href="{{ url_for('home') }}" class="back-link">返回主页</a>
    </div>
</body>
</html>
'''

profile_template = '''
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>个人中心</title>
    <style>
        body { font-family: "微软雅黑", Arial, sans-serif; background: #fff; margin:0;}
        .profile-container { display: flex; }
        .profile-sidebar {
            width: 220px; background: #2566c6; color: #fff; min-height: 100vh; border-radius: 24px 0 0 24px;
            display: flex; flex-direction: column; align-items: center; padding-top: 40px;
        }
        .profile-sidebar .avatar { width: 80px; height: 80px; border-radius: 50%; background: #fff; margin-bottom: 20px; }
        .profile-sidebar .nickname { font-size: 22px; margin-bottom: 30px; color: #fff; }
        .profile-sidebar ul { list-style: none; padding: 0; width: 100%; }
        .profile-sidebar li {
            margin: 18px auto; width: 160px; height: 40px; background: #fff; color: #2566c6;
            border-radius: 20px; text-align: center; line-height: 40px; font-size: 18px; cursor: pointer;
            transition: background 0.2s, color 0.2s; border: 2px solid #2566c6;
        }
        .profile-sidebar li.active, .profile-sidebar li:hover { background: #e3f0ff; color: #1e4e9e; }
        .profile-main { flex: 1; padding: 40px; }
        .profile-title { font-size: 28px; font-weight: bold; margin-bottom: 24px; }
        .profile-content { background: #eaf6fd; border-radius: 12px; padding: 32px; min-height: 400px; }
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; margin-bottom: 8px; }
        .form-group input, .form-group select { width: 300px; padding: 8px; border-radius: 6px; border: 1px solid #ccc; }
        .form-actions { margin-top: 20px; }
        .form-actions button { padding: 8px 24px; border-radius: 6px; border: none; background: #2566c6; color: #fff; font-size: 16px; cursor: pointer;}
        .form-actions button:hover { background: #1e4e9e; }
        table { width: 100%; border-collapse: collapse; background: #fff; }
        th, td { border: 1px solid #bfc9d9; padding: 10px; text-align: left; }
        th { background: #f4faff; }
    </style>
</head>
<body>
<div class="profile-container">
    <div class="profile-sidebar">
        <img src="{{ url_for('static', filename='avatar.png') }}" class="avatar">
        <div class="nickname">{{ nickname }}</div>
        <ul>
            <li class="{% if tab=='history' %}active{% endif %}"><a href="{{ url_for('profile', tab='history') }}" style="color:inherit;text-decoration:none;">浏览记录</a></li>
            {% if role == '学生' %}
            <li class="{% if tab=='questions' %}active{% endif %}"><a href="{{ url_for('profile', tab='questions') }}" style="color:inherit;text-decoration:none;">我的提问</a></li>
            {% elif role == '教师' %}
            <li class="{% if tab=='answers' %}active{% endif %}"><a href="{{ url_for('profile', tab='answers') }}" style="color:inherit;text-decoration:none;">我的解答</a></li>
            {% endif %}
            <li class="{% if tab=='info' %}active{% endif %}"><a href="{{ url_for('profile', tab='info') }}" style="color:inherit;text-decoration:none;">个人信息</a></li>
            <li class="{% if tab=='password' %}active{% endif %}"><a href="{{ url_for('profile', tab='password') }}" style="color:inherit;text-decoration:none;">修改密码</a></li>
        </ul>
    </div>
    <div class="profile-main">
        <div class="profile-title">
            {% if tab=='history' %}浏览记录
            {% elif tab=='questions' %}我的提问
            {% elif tab=='answers' %}我的解答
            {% elif tab=='info' %}个人信息
            {% elif tab=='password' %}修改密码
            {% endif %}
        </div>
        <div class="profile-content">
            {{ content|safe }}
        </div>
    </div>
</div>
</body>
</html>
'''

# 论坛页面路由
@app.route('/forum', methods=['GET', 'POST'])
@login_required
def forum_page():
    # 教师编辑回答
    if request.method == 'POST' and session.get('role') == '教师':
        post_id = request.form.get('post_id')
        teacher_answer = request.form.get('teacher_answer')
        post = ForumPost.query.get(post_id)
        if post:
            post.teacher_answer = teacher_answer
            post.teacher_username = session.get('username')  # 记录答复教师
            db.session.commit()

    # 热点问题统计
    hot_questions = db.session.query(
        ForumPost.question, func.count(ForumPost.id).label('count')
    ).group_by(ForumPost.question).order_by(func.count(ForumPost.id).desc()).limit(5).all()

    # 获取所有帖子，按问题分组
    posts = ForumPost.query.order_by(ForumPost.created_at.desc()).all()
    question_dict = {}
    for post in posts:
        q = post.question
        if q not in question_dict:
            question_dict[q] = {
                "question": q,
                "username": post.username,
                "answers": [],
                "id": post.id,
                "teacher_answer": None
            }
        # 收集所有AI答复
        for ans in post.answers:
            question_dict[q]["answers"].append(ans.answer)
        if post.teacher_answer:
            question_dict[q]["teacher_answer"] = post.teacher_answer
    forum_list = list(question_dict.values())
    return render_template_string(
        forum_template,
        forum=forum_list,
        hot_questions=hot_questions,
        is_teacher=(session.get('role') == '教师')
    )

# 知识库页面路由（优化版，教师可上传，学生仅可下载，支持检索）
@app.route('/repository', methods=['GET', 'POST'])
@login_required
def repository():
    role = session.get('role')
    can_upload = (role == '教师')
    files = os.listdir(UPLOAD_FOLDER)
    keyword = request.args.get('q', '').strip()
    # 检索功能：根据关键词过滤文件名
    if keyword:
        files = [f for f in files if keyword.lower() in f.lower()]
    if can_upload and request.method == 'POST':
        uploaded_files = request.files.getlist('files')
        for file in uploaded_files:
            if file and allowed_file(file.filename):
                file.save(os.path.join(UPLOAD_FOLDER, file.filename))
        flash('文件上传成功！')
        return redirect(url_for('repository'))
    return render_template_string(
        repository_template,
        files=files,
        can_upload=can_upload,
        keyword=keyword
    )
    
#文件下载路由
@app.route('/repository/download/<filename>')
@login_required
def download_file(filename):
    return send_from_directory(UPLOAD_FOLDER, filename, as_attachment=True)

# 个人中心页面模板
@app.route('/profile', methods=['GET', 'POST'])
@login_required
def profile():
    tab = request.args.get('tab', 'history')
    role = session.get('role')
    username = session.get('username')
    user = User.query.filter_by(username=username).first()
    nickname = user.username
    content = ""
    # 浏览记录
    if tab == 'history':
        if role == '学生':
            questions = ForumPost.query.filter_by(username=username).order_by(ForumPost.created_at.desc()).all()
            content = "<table><tr><th>问题</th><th>时间</th></tr>" + "".join(
                f"<tr><td>{q.question}</td><td>{q.created_at}</td></tr>" for q in questions
            ) + "</table>"
        elif role == '教师':
            answers = ForumAnswer.query.join(ForumPost, ForumAnswer.post_id==ForumPost.id)\
                .filter(ForumPost.username==username).order_by(ForumAnswer.created_at.desc()).all()
            content = "<table><tr><th>解答内容</th><th>问题</th><th>时间</th></tr>" + "".join(
                f"<tr><td>{a.answer}</td><td>{a.post.question}</td><td>{a.created_at}</td></tr>" for a in answers
            ) + "</table>"
    # 我的提问
    elif tab == 'questions' and role == '学生':
        questions = ForumPost.query.filter_by(username=username).order_by(ForumPost.created_at.desc()).all()
        content = "<table><tr><th>问题</th><th>时间</th></tr>" + "".join(
            f"<tr><td>{q.question}</td><td>{q.created_at}</td></tr>" for q in questions
        ) + "</table>"
    # 我的解答
    elif tab == 'answers' and role == '教师':
        posts = ForumPost.query.filter(
            ForumPost.teacher_username == username,
            ForumPost.teacher_answer.isnot(None)
        ).order_by(ForumPost.created_at.desc()).all()
        content = "<table><tr><th>问题</th><th>我的答复</th><th>时间</th></tr>" + "".join(
            f"<tr><td>{p.question}</td><td>{p.teacher_answer}</td><td>{p.created_at}</td></tr>" for p in posts
        ) + "</table>"
    # 个人信息
    elif tab == 'info':
        if request.method == 'POST':
            new_username = request.form.get('username')
            new_major = request.form.get('major')
            if new_username and new_major:
                user.username = new_username
                user.major = new_major
                db.session.commit()
                session['username'] = new_username
                session['major'] = new_major
                content = "<div style='color:green;'>修改成功！</div>"
        content += f'''
        <form method="post">
            <div class="form-group"><label>用户名</label><input name="username" value="{user.username}"></div>
            <div class="form-group"><label>专业</label><input name="major" value="{user.major or ''}"></div>
            <div class="form-actions"><button type="submit">保存修改</button></div>
        </form>
        '''
    # 修改密码
    elif tab == 'password':
        if request.method == 'POST':
            old = request.form.get('old_password')
            new = request.form.get('new_password')
            if old and new and old == user.password:
                user.password = new
                db.session.commit()
                content = "<div style='color:green;'>密码修改成功！</div>"
            else:
                content = "<div style='color:red;'>原密码错误或新密码为空！</div>"
        content += '''
        <form method="post">
            <div class="form-group"><label>原密码</label><input type="password" name="old_password"></div>
            <div class="form-group"><label>新密码</label><input type="password" name="new_password"></div>
            <div class="form-actions"><button type="submit">修改密码</button></div>
        </form>
        '''
    return render_template_string(profile_template, tab=tab, role=role, nickname=nickname, content=content)

# 管理员主页
@app.route('/admin')
@login_required
def admin_home():
    if session.get('role') != '管理员':
        return redirect(url_for('home'))
    return render_template_string(admin_template)

# 管理员知识库管理
@app.route('/admin/repository', methods=['GET'])
@login_required
def admin_repository():
    if session.get('role') != '管理员':
        return redirect(url_for('home'))
    files = os.listdir(UPLOAD_FOLDER)
    return render_template_string(admin_repository_template, files=files)

# 管理员删除文件
@app.route('/admin/repository/delete/<filename>', methods=['POST'])
@login_required
def admin_delete_file(filename):
    if session.get('role') != '管理员':
        return redirect(url_for('home'))
    file_path = os.path.join(UPLOAD_FOLDER, filename)
    if os.path.exists(file_path):
        os.remove(file_path)
    return redirect(url_for('admin_repository'))

# 管理员论坛管理
@app.route('/admin/forum', methods=['GET'])
@login_required
def admin_forum():
    if session.get('role') != '管理员':
        return redirect(url_for('home'))
    posts = ForumPost.query.order_by(ForumPost.created_at.desc()).all()
    return render_template_string(admin_forum_template, posts=posts)

# 管理员删除问题（连同所有答案）
@app.route('/admin/forum/delete_post/<int:post_id>', methods=['POST'])
@login_required
def admin_delete_post(post_id):
    if session.get('role') != '管理员':
        return redirect(url_for('home'))
    post = ForumPost.query.get(post_id)
    if post:
        db.session.delete(post)
        db.session.commit()
    return redirect(url_for('admin_forum'))

# 管理员删除AI答复（不影响问题和教师答复）
@app.route('/admin/forum/delete_answer/<int:post_id>/<int:answer_id>', methods=['POST'])
@login_required
def admin_delete_answer(post_id, answer_id):
    if session.get('role') != '管理员':
        return redirect(url_for('home'))
    answer = ForumAnswer.query.get(answer_id)
    if answer:
        db.session.delete(answer)
        db.session.commit()
    return redirect(url_for('admin_forum'))


# 管理员删除教师答复（不影响问题和AI答复）
@app.route('/admin/forum/delete_teacher_answer/<int:post_id>', methods=['POST'])
@login_required
def admin_delete_teacher_answer(post_id):
    if session.get('role') != '管理员':
        return redirect(url_for('home'))
    post = ForumPost.query.get(post_id)
    if post:
        post.teacher_answer = None
        db.session.commit()
    return redirect(url_for('admin_forum'))


# 侧边功能栏模块
sidebar_modules = [
    "学术搜索",
    "期刊文献",
    "学者信息",
    "知识库管理",
    "实验与计算工具"
]

# 简单主页模板
template = '''
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>智能问答与知识服务平台</title>
    <style>
        body { font-family: "微软雅黑", Arial, sans-serif; margin: 0; background: #f5f6fa;}
        .container { display: flex; }
        .sidebar {
            width: 220px; background: #2d3a4b; color: #fff; min-height: 100vh; padding: 30px 0;
        }
        .sidebar h2 { text-align: center; font-size: 22px; margin-bottom: 30px;}
        .sidebar ul { list-style: none; padding: 0;}
        .sidebar li { padding: 12px 30px; cursor: pointer;}
        .sidebar li:hover { background: #1a2230;}
        .main { flex: 1; padding: 40px 60px;}
        .search-box { display: flex; margin-bottom: 30px;}
        .search-box input { flex: 1; padding: 12px; font-size: 16px; border: 1px solid #ccc; border-radius: 4px 0 0 4px;}
        .search-box button { padding: 12px 24px; border: none; background: #3b7ddd; color: #fff; font-size: 16px; border-radius: 0 4px 4px 0; cursor: pointer;}
        .answer-modes { margin: 10px 0 20px 0;}
        .answer-modes label { margin-right: 18px;}
        .recommended { background: #fff; padding: 24px; border-radius: 8px; box-shadow: 0 2px 8px #eee;}
        .recommended h3 { margin-top: 0;}
        .recommended ul { padding-left: 20px;}
        .history { margin-top: 30px; background: #fff; padding: 18px; border-radius: 8px;}
        .personal { margin-top: 30px; background: #eaf0fb; padding: 18px; border-radius: 8px;}
    </style>
</head>
<body>
    <div class="container">
        <div class="sidebar">
            <h2>功能导航</h2>
            <ul>
                {% for module in sidebar_modules %}
                <li>{{ module }}</li>
                {% endfor %}
            </ul>
        </div>
        <div class="main">
    <h1>智能问答与知识服务平台</h1>
    <div style="text-align:right;">
        <a href="{{ url_for('logout') }}" style="color:#3b7ddd;">退出登录</a>
    </div>
    <form class="search-box" method="post">
        <input type="text" name="question" placeholder="请输入您的学术或学习问题..." value="{{ question|default('') }}">
        <button type="submit">提问</button>
    </form>
            <div class="answer-modes">
                <label><input type="radio" name="mode" value="简洁" {% if mode=='简洁' %}checked{% endif %}> 简洁</label>
                <label><input type="radio" name="mode" value="详细" {% if mode=='详细' %}checked{% endif %}> 详细</label>
                <label><input type="radio" name="mode" value="带引用" {% if mode=='带引用' %}checked{% endif %}> 带引用</label>
            </div>
            {% if answer %}
            <div class="history">
                <strong>您的问题：</strong> {{ question }}<br>
                <strong>答复（{{ mode }}）：</strong> {{ answer }}
            </div>
            {% endif %}
            <div class="recommended">
                <h3>推荐问题与主题导航</h3>
                <ul>
                    {% for q in recommended_questions %}
                    <li>{{ q }}</li>
                    {% endfor %}
                </ul>
            </div>
            <div class="personal">
                <strong>个性化与交互：</strong>
                <ul>
                    <li>历史对话追溯</li>
                    <li>订阅最新学术进展</li>
                    <li>跨端使用支持</li>
                </ul>
            </div>
        </div>
    </div>
</body>
</html>
'''

def get_answer(question, mode):
    if not question:
        return ""
    api_key = "sk-604669f6c0554500b96549d52fccaaad"  # 建议生产环境不要明文写密钥
    url = "https://api.deepseek.com/v1/chat/completions"  # DeepSeek API 地址
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    prompt = (
        f"请用{mode}模式回答以下问题，并且答案必须包含：\n"
        f"1. 解题步骤\n"
        f"2. 核心知识点\n"
        f"3. 参考资料\n"
        f"问题：{question}"
    )
    data = {
        "model": "deepseek-chat",  # DeepSeek 的模型名，具体以官方文档为准
        "messages": [{"role": "user", "content": prompt}],
        "max_tokens": 512
    }
    try:
        resp = requests.post(url, headers=headers, json=data, timeout=20)
        resp.raise_for_status()
        result = resp.json()
        return result["choices"][0]["message"]["content"].strip()
    except Exception as e:
        return f"AI服务调用失败：{e}"
    
def get_questions_from_ai(prompt):
    api_key = "sk-604669f6c0554500b96549d52fccaaad"
    url = "https://api.deepseek.com/v1/chat/completions"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    data = {
        "model": "deepseek-chat",
        "messages": [{"role": "user", "content": prompt}],
        "max_tokens": 512
    }
    try:
        resp = requests.post(url, headers=headers, json=data, timeout=20)
        resp.raise_for_status()
        result = resp.json()
        return result["choices"][0]["message"]["content"].strip()
    except Exception as e:
        return f"AI服务调用失败：{e}"

def generate_personalized_resources(major, n=5):
    prompt = (
        f"请为专业或兴趣为“{major}”的大学生推荐{n}个优质学习资源，每个资源只给出名称和一个词语简要说明用途，用“资源名：用途”格式输出，每个资源独立成行，不要详细描述。"
    )
    ai_result = get_questions_from_ai(prompt)
    resources = [line.strip(" 0123456789.、") for line in ai_result.split('\n') if line.strip()]
    return resources

def generate_excellent_questions(major, n=10):
    prompt = (
        f"请你以专业或兴趣为“{major}”的大学生的视角，列举{n}个优质学术问题，内容涵盖学习方法、科研、论文写作、考试准备等，每个问题独立成行，只输出问题本身，不要输出任何解答。"
    )
    ai_result = get_questions_from_ai(prompt)
    questions = [line.strip(" 0123456789.、") for line in ai_result.split('\n') if line.strip()]
    return questions

def is_question_related_to_major(question, major):
    """
    用AI判断问题与专业的相关性，返回True/False
    """
    prompt = (
        f"请判断以下问题是否与“{major}”专业密切相关，只回答“相关”或“不相关”，不要解释。\n"
        f"问题：{question}"
    )
    ai_result = get_questions_from_ai(prompt)
    return "相关" in ai_result

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)